package com.hu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.reggie.common.CustomException;
import com.hu.reggie.mapper.CategoryMapper;
import com.hu.reggie.pojo.Category;
import com.hu.reggie.pojo.Dish;
import com.hu.reggie.pojo.Setmeal;
import com.hu.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishServiceImpl dishService;
    @Autowired
    private SetmealServiceImpl setmealService;

    // 根据id删除分类，在删除之前要判断是否有关联的菜品
    @Override
    public void remove(Long id) {
        // 根据分类id查询菜品
        // 创建条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        // 添加条件
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count=dishService.count(dishLambdaQueryWrapper);
        if(count >0){
            // 有菜品关联抛出异常
            throw new CustomException("分类下还有菜品，不能删除");
        }

        // 根据分类id查询套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        count=setmealService.count(setmealLambdaQueryWrapper);
        if (count >0){
            throw new CustomException("分类下还有套餐，不能删除");
        }

        // 正常删除
        super.removeById(id);
    }
}
